#include "WebSocketServer.h"
#include <iostream>

WebSocketServer::WebSocketServer(int port) : port(port) {
    protocols[0] = {
        "mrcore",
        WebSocketServer::callback,
        0,
        128,
    };
    protocols[1] = { NULL, NULL, 0, 0 }; // terminator

    struct lws_context_creation_info info;
    memset(&info, 0, sizeof(info));
    info.port = port;
    info.protocols = protocols;

    context = lws_create_context(&info);
    if (!context) {
        std::cerr << "lws_create_context failed" << std::endl;
        throw std::runtime_error("Failed to create WebSocket context");
    }
}

WebSocketServer::~WebSocketServer() {
    lws_context_destroy(context);
}

void WebSocketServer::run() {
    while (lws_service(context, 1000) >= 0) {
        // Run the event loop
    }
}

int WebSocketServer::callback(struct lws *wsi, enum lws_callback_reasons reason,
                              void *user, void *in, size_t len) {
    switch (reason) {
        case LWS_CALLBACK_ESTABLISHED:
            std::cout << "Connection established" << std::endl;
            break;
        case LWS_CALLBACK_RECEIVE:
            std::cout << "Received data: " << std::string((char *)in, len) << std::endl;
            lws_write(wsi, (unsigned char *)in, len, LWS_WRITE_TEXT);
            break;
        case LWS_CALLBACK_CLOSED:
            std::cout << "Connection closed" << std::endl;
            break;
        default:
            break;
    }
    return 0;
}